package com.cubesugar2014.pickupscreen;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;



import com.cubesugar2014.pickupscreen.MainActivity;
import com.cubesugar2014.pickupscreen.R;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.app.ActivityManager.RecentTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.telephony.SmsManager;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;

public class SService extends Service {

	
	static public void FLOG(String text)
	{       
/*	   File logFile = new File("sdcard/log_wc.txt");
	   if (!logFile.exists())
	   {
	      try
	      {
	         logFile.createNewFile();
	      } 
	      catch (IOException e)
	      {
	         // TODO Auto-generated catch block
	         e.printStackTrace();
	      }
	   }
	   try
	   {
	      //BufferedWriter for performance, true to set append to file flag
	      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
	      buf.append(text);
	      buf.newLine();
	      buf.flush();
	      buf.close();
	   }
	   catch (IOException e)
	   {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	   }
	*/
	}
	
	
	public static final String PREFS_NAME = "PUSPrefsFile";

	private NotificationManager  mManager; 
	private Notification.Builder mBuilder;
	
	private ActivityManager mActivityManager;
		

	private SensorManager sensorManager;
	private AccListener listen;
	
	static public boolean mOnWorking = false;
    private SharedPreferences mSettings;
	
    private static Timer timer = new Timer(); 
    
    private long mActivateTick;
    
    // Unique Identification Number for the Notification.
    // We use it on Notification start, and to cancel it.
    private int NOTIFICATION = 91025;
    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
    	SService getService() {
            return SService.this;
        }
    }


    static float accX = 0.0f;
 	static float accY = 0.0f;
 	static float accZ = 0.0f;
 	 	
	private class AccListener implements SensorEventListener {
		 
 	public float maxM = 0;
 	public Context context;
 	
 	private final int THRESHOLD = 30;//11025;
    
 	private long preEventTime;
 	
 
 	
	public float magnitude(float[] vector) {
	    return (float) Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]
	        + vector[2] * vector[2]);
	  }
	
	  
	public void onAccuracyChanged(Sensor sensor, int accuracy) {    
      }    
	public void onSensorChanged(SensorEvent event) {  
	      
      	/*
          Log.i("SENSOR", "Acceleration changed.");
          Log.i("SENSOR", "  Acceleration X: " + event.values[0]
                        + ", Acceleration Y: " + event.values[1]
                         + ", Acceleration Z: " + event.values[2]);
          
          accX = event.values[0];
          accY = event.values[1];
          accZ = event.values[2];
          		
          float m = magnitude(event.values);
	  
	  */
		
		 // alpha is calculated as t / (t + dT)
        // with t, the low-pass filter's time-constant
        // and dT, the event delivery rate

        final float alpha = 0.8f;

        float gravity[] = new float[3];
        
        gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
        gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
        gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];

        float acc[] = new float[3];
        
        acc[0] = event.values[0] - gravity[0];
        acc[1] = event.values[1] - gravity[1];
        acc[2] = event.values[2] - gravity[2];
        
        float m = magnitude(acc);
        
        
    	//String packageName = mActivityManager.getRunningTasks(1).get(0).topActivity
         
        
        /*
         
         Process sh = Runtime.getRuntime().exec("su", null,null);

                        OutputStream  os = sh.getOutputStream();
                        os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
                        os.flush();

                        os.close();
                        sh.waitFor();

    then read img.png as bitmap and convert it jpg as follows 

Bitmap screen = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+ File.separator +"img.png");

//my code for saving
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        screen.compress(Bitmap.CompressFormat.JPEG, 15, bytes);

//you can create a new file name "test.jpg" in sdcard folder.

File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "test.jpg");
                f.createNewFile();
//write the bytes in file
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
// remember close de FileOutput

        fo.close();
        
         */
        
        
	  }
	}
	
    
    @Override
    public void onCreate() {
    	mManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      	mBuilder = new Notification.Builder(this);
    
       	
        // Display a notification about us starting.  We put an icon in the status bar.
        showNotification();
        
    	mSettings = getSharedPreferences(PREFS_NAME, 0);
    	
    	
    	sensorManager = (SensorManager) getApplicationContext()
	            .getSystemService(SENSOR_SERVICE);
	    listen = new AccListener();
	    Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	    sensorManager.registerListener(listen, accel, SensorManager.SENSOR_DELAY_NORMAL);
	    
	    listen.context = getApplicationContext();
	    
       	if (Build.BRAND.equalsIgnoreCase("generic")) 
       	{
       	   // emulator
       	} else {
       	
       	}
       	
    	mActivityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
        
    	
       	mOnWorking = true;
       	
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
    	
    	timer.cancel();
        // Cancel the persistent notification.
    	mManager.cancel(NOTIFICATION);

        // Tell the user we stopped.
        Toast.makeText(this, "sservice_stopped", Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();

    /**
     * Show a notification while this service is running.
     */
    @SuppressLint("NewApi")
	private void showNotification() {
      	mBuilder.setSmallIcon(R.drawable.ic_launcher);
       	mBuilder.setTicker("PickupScreen service on");
       	mBuilder.setWhen(System.currentTimeMillis());
       	mBuilder.setContentText("PickupScreen in cubesugar 2014 project");
       	mBuilder.setDefaults(Notification.DEFAULT_LIGHTS);
       			//Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
       	mBuilder.setAutoCancel(true);
       	//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, ItemListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
       	//mBuilder.setContentIntent(pendingIntent);
      		 
       	//mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
       	
        // Send the notification.
    	//mManager.notify(NOTIFICATION, mBuilder.build());
    }
    
}

